#pragma once

#include <iostream>
#include <string>
#include <fstream>
#include <unordered_map>
#include "log.hpp"

const std::string defaultdict = "./dict.txt";
const std::string sep = ": ";

using namespace LogModule;

class Dict
{
public:
    Dict(const std::string& path = defaultdict) : _dict_path(path)
    {}
    bool DictLoad()
    {
        //打开字典
        std::fstream in(_dict_path);
        if(!in.is_open())
        {
            LOG(LogLevel::DEBUG) << "打开字典失败";
            return false;
        }

        std::string line;
        while(std::getline(in, line))
        {
            auto pos = line.find(sep);
            if(pos == std::string::npos)
            {
                LOG(LogLevel::WARING) << "解析" << line << "失败";
                continue;
            }
            //开始分割，并加入哈希表中
            std::string english = line.substr(0, pos);
            std::string chinese = line.substr(pos + sep.size());
            if(english.empty() || chinese.empty())
            {
                LOG(LogLevel::WARING) << "解析" << line << "失败";
                continue;
            }
            _dic[english] = chinese;
        }

        in.close();
        return true;
    }
    std::string translate(const std::string& word)
    {
        auto it = _dic.find(word);
        if(it == _dic.end())
        {
            return "None";
        }
        return it->second;
    }
private:
    std::string _dict_path;
    std::unordered_map<std::string, std::string> _dic;
};